import axios from 'axios';
import Cookie from 'js-cookie';

const s = axios.create();

s.interceptors.request.use(
  config => {
    // eslint-disable-next-line no-param-reassign
    config.headers.token = Cookie.get('token');
    return config;
  },
  error => Promise.reject(error)
);

s.interceptors.response.use(
  response => {
    if (response.data.code === 1) return response.data.data;
    throw new Error(response.data.msg);
  },
  error => Promise.reject(error)
);

// eslint-disable-next-line import/prefer-default-export
export const http = s;

export const catchAppError = function catchAppError(err) {
  if (err.message === '请登录后操作') {
    window.location.href = '/login';
    return;
  }
  if (err.message !== 'Request aborted') {
    // eslint-disable-next-line no-alert
    alert(err.message);
  }
};

const script = document.createElement('script');
script.type = 'text/javascript';
script.src =
  'https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';

export const mapQQ = script;

export function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}
